package main

import (
	"context"
	"fmt"
	greeter "go_final/demos/grpc_metadata/protofile"
	"time"

	"google.golang.org/grpc/codes"

	grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"

	"google.golang.org/grpc"
)

func main() {
	interceptor := grpc.UnaryClientInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		start := time.Now()
		err := invoker(ctx, method, req, reply, cc)
		fmt.Println("耗时: %s", time.Since(start))
		return err
	})
	retryOpts := []grpc_retry.CallOption{
		grpc_retry.WithMax(3),                           // 设置重试次数
		grpc_retry.WithPerRetryTimeout(time.Second * 1), // 设置每次重试的超时时间
		grpc_retry.WithCodes(codes.Unknown, codes.DeadlineExceeded),
	}

	var opts []grpc.DialOption
	opts = append(opts, grpc.WithInsecure())
	opts = append(opts, grpc.WithUnaryInterceptor(interceptor))
	// 设置全区的重试选项
	opts = append(opts, grpc.WithUnaryInterceptor(grpc_retry.UnaryClientInterceptor(retryOpts...)))

	conn, err := grpc.Dial(":8080", opts...)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	c := greeter.NewGreeterClient(conn)

	res, err := c.SayHi(
		context.Background(),
		&greeter.SayHiRequest{
			Id: "Felix",
		},
		// grpc_retry.WithMax(3),                         // 设置重试次数
		// grpc_retry.WithPerRetryTimeout(time.Second*1), // 设置每次重试的超时时间
		// grpc_retry.WithCodes(codes.Unknown, codes.DeadlineExceeded),
	)
	if err != nil {
		fmt.Println("err: ", err)
		return
	}

	fmt.Println("res", res)
}
